package com.wimcorp.magic.client.input;

import java.util.concurrent.Callable;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.fusesource.jansi.Ansi.Color;

import com.wimcorp.magic.client.CommandLineInterface;

public class BooleanSelector extends Selector implements Callable<Boolean> {

	private String message;
	

	public BooleanSelector(CommandLineInterface commandLineInterface, String message) {
		super(commandLineInterface);
		this.message = message;
	
	}

	@Override
	public Boolean call() throws Exception {
		return selectBoolean(message);
	}

	private boolean selectBoolean(String message) {
		Options options = getSelectBooleanOptions();
		CommandLineParser parser = new DefaultParser();
		ConsoleInput selectConsole = new ConsoleInput();
		while (isRun()) {
			getCommandLineInterface().getMainConsole().cancel();
			getCommandLineInterface().printInstruction(message);
			try {
				CommandLine line = parser.parse(options, selectConsole.readLine().split(" "));
				for (Option option : line.getOptions()) {
					if ("y".equals(option.getOpt())) {
						return true;
					}
					if ("n".equals(option.getOpt())) {
						return false;
					}
				}
				processCommands(options, line.getOptions());
			} catch (Exception e) {
				getCommandLineInterface().print(e.getMessage(), Color.RED);
			}
		}
		return false;
	}
	
	private Options getSelectBooleanOptions() {
		Options options = new Options();
		options.addOption(getHelpOption());
		options.addOption(getSelectYesOption());
		options.addOption(getSelectNoOption());
		options.addOption(getPlayerListOption());
		options.addOption(getViewBattleFieldOption());
		options.addOption(getViewGraveyardOption());
		options.addOption(getViewHandOption());
		options.addOption(getViewLifeOption());
		return options;
	}

}
